package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token==null){
            response.setStatus(401);
            return false;
        }
        User user= finByToken(token);
        if (user==null){
            response.setStatus(401);
            return false;
        }
         UserHolder.setUser(user);
        return true;
    }

    private User finByToken(String token) {
        //从redis中找到缓存的用户User
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (userJson!=null){
            //找到用户后 给用户redis缓存
            redisTemplate.opsForValue().set("TOKEN_"+token,userJson, Duration.ofHours(1));
            return JSON.parseObject(userJson,User.class);
        }
        return null;
    }
}
